package com.example.selenium.core;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.selenium.domain.WaybillDto2;
import com.example.selenium.util.ExcelUtil;
import com.example.selenium.util.IDCardUtil;
import com.example.selenium.util.SSLClient;
import com.example.selenium.util.StringUtils;
import lombok.SneakyThrows;
import org.apache.commons.collections.CollectionUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.Select;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

public class Start2021 {
    protected static Logger logger = LoggerFactory.getLogger(Start2021.class);

    public static Map<String, String> cookieMap = new HashMap<>();

    public static String hostUrl = "https://apit.y2t.com/cockpit-lhk/";

    public static String cookieV = "";

    public static String startT = "2020-10-20 00:00:00";
    public static String endT = "2020-10-21 00:00:00";
    public static String excelName = "20-21.xlsx";

    public static Integer currentNum = 0;

    public static Map<String,String> map = new HashMap<>();

    public static void main(String[] args) throws Exception {

        setCookieMap();
        logger.info("ChromeAutoGetY2TData main args" + JSONObject.toJSONString(args));
        String loginNameV = "13926676253";
        String loginPwdV = "wlys1234";
        String hostUrlNew = "https://apit.y2t.com/cockpit-lhk/login";
        String runPath = "E:\\chromedriver.exe";
        Start2021.hostUrl = hostUrlNew;

        getData(loginNameV, loginPwdV, Start2021.hostUrl, runPath, startT, endT);

    }

    public static void sendkeys(String sts, WebElement we) throws InterruptedException {
        char[] s = sts.toCharArray();
        for (char ss : s) {
            we.sendKeys(String.valueOf(ss));
            Thread.sleep(200);
        }

    }

    private static void setCookieMap() {
        cookieMap.put("cashier-session", "cashier-session");
    }

    public static void getData(String loginUserNameV, String loginPwdV, String hostUrl, String runPath, String startT,
                               String endT) {

        List<WaybillDto2> counts = new ArrayList<>();
        ChromeOptions options = new ChromeOptions();
        // options.addArguments("--test-type", "--ignore-certificate-errors");
        // options.addArguments("--proxy-server=http://localhost:8888");
        System.setProperty("webdriver.chrome.driver", runPath);
        // 避免被反爬虫
        options.setExperimentalOption("excludeSwitches", Arrays.asList("enable-automation"));
        WebDriver driver = new ChromeDriver(options);
        driver.manage().window().setSize(new Dimension(1360, 850));
        try {
            String homeV = "https://apit.y2t.com/cockpit-lhk/index";
            String loginUrlV = "https://apit.y2t.com/cockpit-lhk/login";
            logger.info(driver.getCurrentUrl());
            toLogin(driver, loginUserNameV, loginPwdV, loginUrlV);

            //Thread.sleep(1000 * 10);

//			// 支付列表
//			((JavascriptExecutor) driver).executeScript("document.querySelector(\"#\\\\31 197 > a\").click();");
//			//切换到内容iframe
//			  driver.switchTo().frame(driver.findElement(By.xpath("//*[@id=\"contentFrame\"]")));


            String payRecordUrl = "https://apit.y2t.com/cockpit-lhk/company/pay_settlement/list";
            //直接到支付列表
            driver.get(payRecordUrl);

            if (driver.getCurrentUrl().equals(payRecordUrl)) {
                Thread.sleep(1000);
                // 每页100
                driver.findElement(By.xpath("//*[@id=\"dynamic-table_length\"]/label/select/option[5]")).click();

                Thread.sleep(200);

                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"#bTime\").value='" + startT + "';");
                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"#eTime\").value='" + endT + "';");

                Thread.sleep(1000);
                // 样式 共多少页，多少条
                String currentWeekAll = "";
                String  companyName= "运易通科技有限公司";

                ((JavascriptExecutor) driver).executeScript("document.getElementById(\"companyName\").style.display=\"block\";");
                WebElement companyelement = driver.findElement(By.id("companyName"));
                Select companySelect = new Select(companyelement);
                companySelect.selectByVisibleText(companyName);

                String payStatus="支付成功";
                ((JavascriptExecutor) driver).executeScript("document.getElementById(\"status\").style.display=\"block\";");
                WebElement payStautselement = driver.findElement(By.id("status"));
                Select payStautsSelect = new Select(payStautselement);
                payStautsSelect.selectByVisibleText(payStatus);



//				String jsStr = "window.alert(\"请尽快完支付状态和公司名称的选择！\")";
//				((JavascriptExecutor) driver).executeScript(jsStr);

                Thread.sleep(5000);
                driver.findElement(By.xpath("//*[@id=\"searchDialog\"]")).click();
                Thread.sleep(5000);
                currentWeekAll = driver.findElement(By.xpath("//*[@id=\"dynamic-table_info\"]")).getText();

                // 判断没有运单数据
                if ("未找到任何记录".equalsIgnoreCase(currentWeekAll)) {
                    logger.error(startT + "到" + endT + " 没有数据产生！");
                } else {
                    currentWeekAll = currentWeekAll.split("，")[1].replaceAll("条", "").replaceAll("\n", "")
                            .replaceAll("跳到 页", "").replaceAll(",", "");

                    String currentPage = "";
                    String lastPage = "";
                    do {

                        Thread.sleep(1000 * 10);
                        try {
                            // 坑出现没有数据的情况
                            currentPage = (String) ((JavascriptExecutor) driver).executeScript(
                                    "return document.querySelector(\"#dynamic-table_paginate > ul > li.paginate_button.active\").innerText;");
                            lastPage = ((String) ((JavascriptExecutor) driver)
                                    .executeScript("return document.querySelector(\"#dynamic-table_info\").innerText;"))
                                    .split("，")[0].replaceAll("条", "").replaceAll("\n", "").replaceAll("共", "")
                                    .replaceAll("页", "").replaceAll(",", "");
                            List<WaybillDto2> waybillList = getWayBillInfo(driver.getPageSource(), companyName);
                            // 默认应该是100页
                            for (int i = 0; i < waybillList.size(); i++) {

                                WaybillDto2 billDto = waybillList.get(i);

                                // 点击运单详情
                                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"#dynamic-table > tbody > tr:nth-child("+ (i + 1) + ") > td:nth-child(3) > a\").click();");

                                // 设置运单信息
                                getWaybillDetailInfo(driver,billDto);

                                // 点击基本信息页签1
                                ((JavascriptExecutor)driver).executeScript("document.querySelector(\"#viewDriverDialog > div > div.col-sm-12 > div > ul > li:nth-child(1)\").click();");
                                Thread.sleep(1000);

                                // 点击驾驶证页签3
                                ((JavascriptExecutor)driver).executeScript("document.querySelector(\"#viewDriverDialog > div > div.col-sm-12 > div > ul > li:nth-child(3)\").click();");
                                Thread.sleep(1000);

                                // 点击车辆页签4
                                ((JavascriptExecutor)driver).executeScript("document.querySelector(\"#viewDriverDialog > div > div.col-sm-12 > div > ul > li:nth-child(4)\").click();");
                                Thread.sleep(1000);

                                // 点击第5个页签 获取操作历史，结束时间
                                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"#myTab > li:nth-child(5) > a\").click();");
                                Thread.sleep(1000);

                                // 获取运单开始结束运输时间
                                billDto.setShipmentStartTime((String) ((JavascriptExecutor) driver).executeScript("return	document.querySelector(\"#viewWaybillOperate > div > div > div:nth-child(2) > div.timeline-info > span\").innerText;"));
                                billDto.setShipmentEndTime((String) ((JavascriptExecutor) driver).executeScript("return	document.querySelector(\"#viewWaybillOperate > div > div > div:nth-child(3) > div.timeline-info > span\").innerText;"));

                                // 设置运单相关图片
                                getWaybillImg(driver,billDto);


                                // 关闭运单详情
                                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"body > div:nth-child(5) > div.ui-dialog-titlebar.ui-widget-header.ui-corner-all.ui-helper-clearfix.ui-draggable-handle > button\").click();");
                                Thread.sleep(1000);

                                // 打开司机详情
                                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"#dynamic-table > tbody > tr:nth-child("+ (i + 1) + ") > td:nth-child(4) > span\").click();");
                                Thread.sleep(3000);

                                // 设置司机信息
                                getDriverInfo(driver,  billDto);
                                String driverInfoStr = (String) ((JavascriptExecutor) driver).executeScript("return	document.querySelector(\"#dynamic-table > tbody >  tr:nth-child("+ (i + 1) + ")  > td:nth-child(4)\").innerText;");
                                String[] driverInfo = driverInfoStr.split("\n");
                                billDto.setDriverName(driverInfo[0]);
                                billDto.setCarNumber(driverInfo[1]);
                                billDto.setDriverPhone(driverInfo[2]);





                                // 获取支付信息
                                String payDetail = getPayDetail(billDto.getRelWaybillId());
                                logger.info("payDetail："+payDetail);
                                JSONArray jsonArray = JSONArray.parseArray(payDetail);
                                if(jsonArray!=null && jsonArray.size()>0){
                                    JSONObject jsonObject = (JSONObject) JSON.toJSON(jsonArray.get(jsonArray.size()-1));
                                    String sysNo = jsonObject.getString("sysNo");
                                    String channelFlowNo = jsonObject.getString("payWaybillNo");// 运易通支付流水号

                                    // 获取支付详情
                                    String mainResult = getTransOrderMain(sysNo);
                                    JSONObject mainJson = JSONObject.parseObject(mainResult);
                                    String  status = mainJson.getString("status");
                                    JSONArray array = new JSONArray();
                                    if("true".equals(status)){
                                        String dataStr = mainJson.getString("data");
                                        if(StringUtils.isNotEmpty(dataStr)){
                                            JSONArray mainArray = JSONArray.parseArray(dataStr);
                                            JSONObject entity = new JSONObject();
                                            entity.put("channelFlowNo",channelFlowNo); // 支付流水号 等于运易通的支付单号
                                            for (int j = 0; j < mainArray.size(); j++) {
                                                JSONObject mainJsonObj =(JSONObject) JSON.toJSON(mainArray.get(j));
                                                JSONObject transOrderMain = mainJsonObj.getJSONObject("transOrderMain");
                                                String billType = transOrderMain.getString("billType");

                                                if(StringUtils.isNotEmpty(transOrderMain.getString("transTime"))){
                                                    String newTime = transOrderMain.getString("transTime").substring(0,19).replaceAll("T"," ");
                                                    String transTime = UTCToCST(newTime,"yyyy-MM-dd HH:mm:ss");
                                                    entity.put("orderDate",transTime);
                                                }

                                                if("0".equals(billType)){// 运费
                                                    entity.put("payAmt",transOrderMain.getString("amt"));
                                                    entity.put("payHostFlowNo",transOrderMain.getString("hostFlowNo"));
                                                }
                                                if("1".equals(billType)){// 手续费
                                                    entity.put("feeAmt",transOrderMain.getString("amt"));
                                                    entity.put("feeHostFlowNo",transOrderMain.getString("hostFlowNo"));
                                                }
                                            }
                                            array.add(entity);
                                            billDto.setPayRecord(JSONObject.toJSONString(array));
                                        }
                                    }
                                }
                                counts.add(billDto);
                                System.out.println("第" + i + "条运单相关信息" + JSONObject.toJSONString(billDto));

                                // 关闭司机详情
                                ((JavascriptExecutor) driver).executeScript("document.querySelector(\"body > div.ui-dialog.ui-widget.ui-widget-content.ui-corner-all.ui-front.ui-draggable.ui-resizable > div.ui-dialog-titlebar.ui-widget-header.ui-corner-all.ui-helper-clearfix.ui-draggable-handle > button\").click();");
                                Thread.sleep(1000);
                            }
                            // 计算下一页
                            ((JavascriptExecutor) driver)
                                    .executeScript("document.querySelector(\"#dynamic-table_next > a\").click();");
                        } catch (Exception e) {
                            e.printStackTrace();
                            // 一般真实出现了无数据的情况直接进行下一轮循环
                            currentPage = "ok";
                            lastPage = "ok";
                        }
                    } while (!currentPage.equalsIgnoreCase(lastPage));
                }
            } else {
                logger.error("自动登录出现问题，请联系 开发人员处理！");
            }

        } catch (Exception e) {
            logger.error("获取单周数据错误", e);
            e.printStackTrace();
        } finally {
            // 关闭并退出浏览器
            driver.close();
            driver.quit();
            if(CollectionUtils.isNotEmpty(counts)){
                ExcelUtil<WaybillDto2> util = new ExcelUtil<WaybillDto2>(WaybillDto2.class);
                util.exportExcel(counts, excelName ,"E:/");
            }
        }
        System.out.println(startT + "  to  " + endT + "数据读取完毕！");

    }

    public static String byIdText(WebDriver driver, String id) {
        return driver.findElement(By.id(id)).getAttribute("value");
    }


    public static String getSwitchIdText(WebDriver driver, String id) {
        String result = driver.switchTo().frame(0).findElement(By.id(id)).getText();
        driver.switchTo().defaultContent();
        return result;
    }


    public static Long getSwitchIdMoneyText(WebDriver driver, String id) {
        return new BigDecimal(Double.parseDouble(getSwitchIdText(driver, id))).multiply(new BigDecimal(100)).longValue();
    }

    public static long byIdMoneyText(WebDriver driver, String id) {
        return new BigDecimal(Double.parseDouble(byIdText(driver, id))).multiply(new BigDecimal(100)).longValue();
    }

    public static List<WaybillDto2> getWayBillInfo(String html, String companyName) {
        try {
            org.jsoup.nodes.Document document = Jsoup.parse(html);
            Element table = document.getElementById("dynamic-table");
            List<Element> tbodys = table.getElementsByTag("tbody");
            for (Element tbody : tbodys) {
                List<Element> trs = tbody.getElementsByTag("tr");
                List<WaybillDto2> result = buildDataFromTrs(trs, companyName);
                return result;

            }
        } catch (Exception e) {
            logger.error("获取表单数列表出错 ", e);
            e.printStackTrace();
        }

        return null;
    }

    // trs的数量应该是100个
    private static List<WaybillDto2> buildDataFromTrs(List<Element> trs, String companyName) {
        List<WaybillDto2> datas = new ArrayList<WaybillDto2>();

        for (Element tr : trs) {
            logger.info("正在读取第："+(++currentNum));
            WaybillDto2 data = new WaybillDto2();
            List<Element> tds = tr.getElementsByTag("td");

            String waybillNo = tds.get(1).text().split("-")[0];
            data.setTrackId(waybillNo);
            String waybillEvent = tds.get(2).getElementsByTag("a").attr("onclick"); // 获取运易通的运单id，而不是运单号
            String waybillId = waybillEvent.split(",")[1];
            data.setRelWaybillId(waybillId);

            logger.info("waybillNo："+waybillNo+",waybillId:"+waybillId);
            if(StringUtils.isNotEmpty(map.get(waybillNo))){
                map.put(waybillNo,waybillId);
            }



            String[] incomeInfo = tds.get(4).text().split(" ");
            data.setReciveBankeName(incomeInfo[2]);
            data.setReciveCardNo(incomeInfo[1]);
            data.setReciveName(incomeInfo[0]);
            datas.add(data);
        }
        return datas;
    }

    public static String[] getFeeInfo(String feeInfo) {
        // [无]预付款 0.00 [未]到付款 935.00 [无]回单付 0.00
        feeInfo = feeInfo.replaceAll("\\[无\\]", "").replaceAll("\\[未\\]", "").replaceAll("\\[付\\]", "")
                .replaceAll("预付款", "").replaceAll("到付款", "#").replaceAll("回单付 ", "#").replaceAll(" ", "");
        return feeInfo.split("#");
    }

    public static String[] getStatusInfo(String statusInfo) {
        // [运]已回单 [付]已支付 [票]已开票
        statusInfo = statusInfo.replaceAll("\\[运\\]", "").replaceAll("\\[票\\]", "#").replaceAll("\\[付\\]", "#")
                .replaceAll(" ", "");
        return statusInfo.split("#");
    }

    public static String[] getStartEndInfo(String lineInfo) {
        // [起] 黑龙江省 齐齐哈尔市 富拉尔基区 [止] 黑龙江省 齐齐哈尔市 富拉尔基区
        lineInfo = lineInfo.replaceAll("\\[起\\]", "").replaceAll("\\[止\\]", "#").trim();

        return lineInfo.split("#");
    }



    private static void toLogin(WebDriver driver, String loginEmailV, String loginPwdV, String loginUrl)
            throws InterruptedException {
        driver.get(loginUrl);

        sendkeys(loginEmailV, driver.findElement(By.xpath("//*[@id=\"userName\"]")));

        sendkeys(loginPwdV, driver.findElement(By.xpath("//*[@id=\"passWord\"]")));
        // http://merchant.yxtweb.com/index.html
        String jsStr = "window.alert(\"请尽快完成验证码和用户名的输入！\")";
        ((JavascriptExecutor) driver).executeScript(jsStr);
        do {
            Thread.sleep(1000 * 10);
            logger.info("请输入用户名验证码！");
        } while (loginUrl.equals(driver.getCurrentUrl()));
        logger.info("成功登录运易通，如果有出现同时在线的情况，需要特殊处理，请尽快完成处理!");
        Thread.sleep(1000 * 5);

        // 获取cookie
        getLoginCookie(driver);
    }

    public static String showCookies(WebDriver driver, Map<String, String> changeCookie) {
        Set<Cookie> cookies = driver.manage().getCookies();
        StringBuffer cookiesStr = new StringBuffer("");
        for (Cookie c : cookies) {
            if (changeCookie.containsKey(c.getName())) {
                cookiesStr.append(changeCookie.get(c.getName()) + ";");
            }
            cookiesStr.append(c.toString().split(";")[0] + ";");

        }
        return cookiesStr.toString();
    }


    public static void getWaybillDetailInfo(WebDriver webDriver, WaybillDto2 build){
        // 货物相关
        String goodsName     = webDriver.findElement(By.id("viewGoodsName")).getAttribute("value");
        String goodsAmount   = webDriver.findElement(By.id("viewGoodNumber")).getAttribute("value");
        String goodsType     = webDriver.findElement(By.id("viewGoodsType")).getAttribute("value");
        String bussinessType = webDriver.findElement(By.id("viewBusinessType")).getAttribute("value");
        String projectName   =  webDriver.findElement(By.id("viewProjectName")).getAttribute("value");

        String goodsUnits = "";
        if(StringUtils.isNotEmpty(goodsAmount)){
            char[] chars = goodsAmount.toCharArray();
            String amount = "";
            String unit ="";
            for (int i = 0; i < chars.length; i++) {
                try{
                    if(Integer.parseInt(String.valueOf(chars[i]))>=0){
                        amount+=String.valueOf(chars[i]);
                    }
                }catch (NumberFormatException e){
                    unit= String.valueOf(chars[i]);
                }
            }
            goodsAmount = amount;
            goodsUnits = unit;
        }

        // 托运，收货 地址
        String[] tyDetailAddress = webDriver.findElement(By.id("viewRoutePointAddressStart")).getAttribute("value").split(" ");
        String tyProvince = tyDetailAddress[0];
        String tyCity = "";
        String tyCounty = "";
        if(tyDetailAddress.length==2){
            tyCity = tyDetailAddress[1];
        }else if(tyDetailAddress.length==3){
            tyCity = tyDetailAddress[1];
            tyCounty = tyDetailAddress[2];
        }


        String tyUnits = webDriver.findElement(By.id("viewShipperUnit")).getAttribute("value"); // 托运单位
        String tyContacts = webDriver.findElement(By.id("viewShipperContact")).getAttribute("value"); // 托运联系人
        String tyContactsPhone = webDriver.findElement(By.id("viewShipperPhone")).getAttribute("value"); // 托运联系电话
        String tyDetailAddr = webDriver.findElement(By.id("viewRoutePointAddressStartDetail")).getAttribute("value"); // 托运详细地址

        String[] shDetailAddress =  webDriver.findElement(By.id("viewRoutePointAddressEnd")).getAttribute("value").split(" ");
        String shProvince = shDetailAddress[0];

        String shCity="";
        String shCounty = "";
        if(shDetailAddress.length==2){
            shCity = shDetailAddress[1];
        }else if(shDetailAddress.length==3){
            shCity = shDetailAddress[1];
            shCounty = shDetailAddress[2];
        }

        String shUnits = webDriver.findElement(By.id("viewReceiverUnit")).getAttribute("value");
        String shContacts =  webDriver.findElement(By.id("viewReceiverContact")).getAttribute("value"); // 收货联系人
        String shContactsPhone = webDriver.findElement(By.id("viewReceiverPhone")).getAttribute("value"); // 收货联系电话
        String shDetailAddr = webDriver.findElement(By.id("viewRoutePointAddressEndDetail")).getAttribute("value");

        // 运费信息
        String total = webDriver.findElement(By.id("viewPlanPriceAmt")).getAttribute("value");
        String hd = webDriver.findElement(By.id("viewReceiptMoney")).getAttribute("value"); // 回单押金
        String yf = webDriver.findElement(By.id("viewSendMoney")).getAttribute("value"); // 预付款
        String df = webDriver.findElement(By.id("viewToPayment")).getAttribute("value"); // 到付


        // 起运时间，到达时间
        String shipmentStartTime =  webDriver.findElement(By.id("viewWaybillOperate")).findElements(By.className("clearfix")).get(1).findElement(By.className("timeline-info")).findElement(By.tagName("span")).getText();
        String shipmentEndTime =  webDriver.findElement(By.id("viewWaybillOperate")).findElements(By.className("clearfix")).get(2).findElement(By.className("timeline-info")).findElement(By.tagName("span")).getText();
        String waybillCreateTime = webDriver.findElement(By.id("viewCreatedTime")).getAttribute("value");// 运单创建时间

        build.setWaybillCreateTime(waybillCreateTime);
        build.setGoodsName(goodsName);
        build.setGoodsAmount(goodsAmount);
        build.setGoodsType(goodsType);
        build.setBussinessType(bussinessType);
        build.setProjectName(projectName);
        build.setTyProvince(tyProvince);
        build.setTyCity(tyCity);
        build.setTyCounty(tyCounty);
        build.setTyUnits(tyUnits);
        build.setTyContacts(tyContacts);
        build.setTyContactsPhone(tyContactsPhone);
        build.setTyDetailAddr(tyDetailAddr);
        build.setShProvince(shProvince);
        build.setShCity(shCity);
        build.setShCounty(shCounty);
        build.setShUnits(shUnits);
        build.setShContacts(shContacts);
        build.setShContactsPhone(shContactsPhone);
        build.setShDetailAddr(shDetailAddr);
        build.setTotal(total);
        build.setHd(hd);
        build.setYf(yf);
        build.setDf(df);
        build.setShipmentStartTime(shipmentStartTime);
        build.setShipmentEndTime(shipmentEndTime);
        build.setGoodsUnits(goodsUnits);
    }


    /**
     * 获取司机相关的信息
     * @param webDriver
     * @param build
     */
    public static void getDriverInfo(WebDriver webDriver,WaybillDto2 build){
        String driverName = webDriver.findElement(By.id("viewIDcardName")).getAttribute("value"); // 司机姓名
        //String driverPhone =  webDriver.findElement(By.id("viewCarPhne")).getAttribute("value"); // 司机手机号
        String driverIdCard = webDriver.findElement(By.id("viewIDcardNumber")).getAttribute("value"); // 司机身份证号
        String idCardAddress = webDriver.findElement(By.id("viewIDcardAddress")).getAttribute("value"); // 司机身份证地址
        //	String driverSex =webDriver.findElement(By.cssSelector("input[name='viewIDcardGender'][[checked=checked]")).getAttribute("value");
        String driverNation = webDriver.findElement(By.id("viewIDcardNationality")).getAttribute("value"); // 司机民族
        String driverBornDate = webDriver.findElement(By.id("viewIDcardDateBirth")).getAttribute("value"); // 司机出生日期
        String idCardOffice  = webDriver.findElement(By.id("viewIDcardOffice")).getAttribute("value"); // 身份证签发机关
        String idCardStartDate = webDriver.findElement(By.id("viewIDcardNegativeFirstDate")).getAttribute("value"); // 身份证开始时间
        String idCardEndDate = webDriver.findElement(By.id("viewIDcardNegativeLastDate")).getAttribute("value"); // 身份证结束时间
        String idCardFrontImgUrl = webDriver.findElement(By.id("viewDriverIDcardUploads")).getAttribute("src"); // 身份证正面图片
        String idCardBackImgUrl  = webDriver.findElement(By.id("viewDriverIDcardNegativeUploads")).getAttribute("src"); // 身份证反面图片
        String driverNationality =  webDriver.findElement(By.id("viewDriverCitizenship")).getAttribute("value"); // 国籍
        String drivingCarType = webDriver.findElement(By.id("viewDriverQuasiDrivingModel")).getAttribute("value"); // 准驾车型
        String driverLicenseStartDate =  webDriver.findElement(By.id("viewDriverEffectiveDateStart")).getAttribute("value"); // 驾驶证开始时间
        String driverLicenseEndDate  =  webDriver.findElement(By.id("viewDriverEffectiveDateEnd")).getAttribute("value"); // 驾驶证结束时间
        String driverLicenseGetDateFirst =  webDriver.findElement(By.id("viewDriverInitialLicenseDate")).getAttribute("value"); // 驾驶证初次领证日期
        String driverLicenseImgUrl = webDriver.findElement(By.id("viewDriverLicenseUploads")).getAttribute("src"); // 驾驶证正面图片链接地址
        //String carNumber = webDriver.findElement(By.id("viewDrivingLicenseNumber")).getAttribute("value"); // 车牌号
        String carLength = webDriver.findElement(By.id("viewDrivingVehicleLength")).getAttribute("value"); // 车长米 ;
        String carWidth = webDriver.findElement(By.id("viewDrivingCarWidth")).getAttribute("value"); // 车宽米 ;
        String carHeight = webDriver.findElement(By.id("viewDrivingCarHeight")).getAttribute("value"); // 车高 分米 ;
        if(StringUtils.isNotEmpty(carHeight)){
            carHeight = new BigDecimal(carHeight).divide(new BigDecimal("10")).setScale(2,BigDecimal.ROUND_HALF_UP).toString();
        }
        String tonnage = webDriver.findElement(By.id("viewDrivingTonnage")).getAttribute("value"); // 核定载重 ;
        String carType =  webDriver.findElement(By.id("viewDrivingLiceVehicleType")).getAttribute("value"); // 车辆类型
        String carColor =  webDriver.findElement(By.id("viewDrivingVehicleColor")).getAttribute("value");  // 车辆颜色
        String carOwner = webDriver.findElement(By.id("viewDrivingOwner")).getAttribute("value"); // 车辆所属人
        String carAddress = webDriver.findElement(By.id("viewDrivingAddress")).getAttribute("value"); // 车辆地址
        String userType = webDriver.findElement(By.id("viewDrivingNatureUse")).getAttribute("value"); // 使用性质
        String model =  webDriver.findElement(By.id("viewDrivingBrandModel")).getAttribute("value"); // 品牌型号
        String carIdentyCode = webDriver.findElement(By.id("viewDrivingIdentificationCode")).getAttribute("value");// 车辆识别代码
        String carEngineNumber = webDriver.findElement(By.id("viewDrivingEngineNumber")).getAttribute("value");  // 发动机号
        String energyType = "柴油"; // 能源类型
        String registerDate = webDriver.findElement(By.id("viewDrivingRegisterDate")).getAttribute("value"); // 注册日期
        String issueDate = webDriver.findElement(By.id("viewDrivingDateIssue")).getAttribute("value"); // 发证日期
        String drivingImgUrl =  webDriver.findElement(By.id("viewDrivingLicenseUploads")).getAttribute("src"); // 行驶证图片图片

        //build.setDriverName(driverName);
        build.setDriverIdCard(StringUtils.isNotEmpty(driverIdCard)?driverIdCard: IDCardUtil.generateID());
        build.setIdCardAddress(StringUtils.isNotEmpty(idCardAddress)?idCardAddress:IDCardUtil.generateID());
        build.setDriverSex("男");
        build.setDriverNation(StringUtils.isNotEmpty(driverNation)?driverNation:"汉");
        //build.setDriverPhone(driverPhone);
        build.setDriverBornDate(driverBornDate);
        build.setIdCardOffice(idCardOffice);
        build.setIdCardStartDate(idCardStartDate);
        build.setIdCardEndDate(idCardEndDate);
        build.setIdCardFrontImgUrl(idCardFrontImgUrl);
        build.setIdCardBackImgUrl(idCardBackImgUrl);
        build.setDriverNationality(driverNationality);
        build.setDrivingCarType(drivingCarType);
        build.setDriverLicenseStartDate(driverLicenseStartDate);
        build.setDriverLicenseEndDate(driverLicenseEndDate);
        build.setDriverLicenseGetDateFirst(driverLicenseGetDateFirst);
        build.setDriverLicenseImgUrl(driverLicenseImgUrl);
        //build.setCarNumber(carNumber);
        build.setCarLength(carLength);
        build.setCarWidth(carWidth);
        build.setCarHeight(carHeight);
        build.setTonnage(tonnage);
        build.setCarType(carType);
        build.setCarColor(carColor);
        build.setCarOwner(carOwner);
        build.setCarAddress(carAddress);
        build.setUserType(userType);
        build.setModel(model);
        build.setCarEngineNumber(carEngineNumber);
        build.setCarIdentyCode(carIdentyCode);
        build.setEnergyType(energyType);
        build.setRegisterDate(registerDate);
        build.setIssueDate(issueDate);
        build.setDrivingImgUrl(drivingImgUrl);
    }

    /**
     * 获取支付记录
     * @param waybillId
     */
    @SneakyThrows
    public static String getPayDetail(String waybillId){
        String requestUrl = "https://apit.y2t.com/cockpit-lhk/proxy/waybillmanagement/queryPayDetail?wayBillId="+waybillId+"&_="+new Date().getTime();
        String result = request(requestUrl);
        logger.info("getPayDetail result："+result);
        return result;
    }

    /**
     * 获取交易订单Main
     */
    @SneakyThrows
    public static String getTransOrderMain(String sysNo){
        String requestUrl = "https://apit.y2t.com/cockpit-lhk/proxy/settlement/Finance/getTransOrderMain?sysNo="+sysNo+"&applyStatus=-1&_="+new Date().getTime();
        String result = request(requestUrl);
        logger.info("getTransOrderMain result："+result);
        return result;
    }

    public static void getLoginCookie(WebDriver webDriver){
        String jsessionIdCookie = "";
        String sinoSSOCookie = "";
        Set<Cookie> cookies = webDriver.manage().getCookies();

        Iterator<Cookie> iterator = cookies.iterator();
        while (iterator.hasNext()){
            Cookie next = iterator.next();
            if(next.getName().equalsIgnoreCase("JSESSIONID")){
                jsessionIdCookie =next.getValue();
                continue;
            }
            if(next.getName().equalsIgnoreCase("SinoSSO")){
                sinoSSOCookie =next.getValue();
                continue;
            }
        }
        if(StringUtils.isAnyEmpty(jsessionIdCookie,sinoSSOCookie)){
            logger.error("获取登录Cookie失败！");
            String jsStr = "window.alert(\"获取用户登录后的Cookie失败,会导致获取不到运单的支付记录，请核对！\")";
            ((JavascriptExecutor) webDriver).executeScript(jsStr);
        }
        cookieV = "JSESSIONID="+jsessionIdCookie+"; SinoSSO="+sinoSSOCookie;
    }


    @SneakyThrows
    public static String request(String url){
        CloseableHttpClient client = new SSLClient();
        String result ="";
        try {
            HttpGet httpGet = new HttpGet(url);
            httpGet.addHeader("cookie",cookieV);
            HttpResponse response = client.execute(httpGet);
            result =  EntityUtils.toString(response.getEntity());
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String UTCToCST(String UTCStr, String format) throws ParseException {
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        date = sdf.parse(UTCStr);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
        return sdf.format(calendar.getTime());
    }

    /**
     * 获取运单相关图片
     * @param driver
     * @param billDto
     */
    public static void getWaybillImg(WebDriver driver,WaybillDto2 billDto){
        List<WebElement> elements = driver.findElements(By.cssSelector("#viewWaybillRelatedPic li"));
        String waybillImgs = "";
        for (int j = 0; j < elements.size(); j++) {
            String imgs = elements.get(j).findElement(By.tagName("img")).getAttribute("src");
            waybillImgs+=(","+imgs);
        }
        // 获取运单相关图片
        if(StringUtils.isNotEmpty(waybillImgs)){
            billDto.setWaybillImg(waybillImgs.substring(1));
        }
    }
}
